<?php

namespace console\controllers;

use common\services\myhtsq\ContactService;
use console\entities\ErpBusinessUnitEntity;
use yii\console\Controller;
use linslin\yii2\curl\Curl;
use console\entities\ErpUserEntity;
use yii\helpers\Json;


/**
 * Erp Api interface interchange
 * erp api 接口调用
 * @author wangwx 2015-6-9
 */
class ErpApiController extends Controller{


	/**
	 * 同步erp api组织用户
	 * @author wangwx
	 */
	public function actionSyncErpUserAndErpBusinessUnit() {
		//@todo 同步数据
        ini_set('max_execution_time', 1200);
        ini_set('default_socket_timeout', 600);
        $wsdl = "http://ekp.mingyuanyun.com/EKPWebService/AdUserService.asmx?wsdl";
        $msg = '';

        $soap = new \SoapClient($wsdl);
        $obj = $soap->GetBusinessUnitAllCol();
        $data = $obj->GetBusinessUnitAllColResult;
        $arr = json_decode($data, true);
        if (empty($arr)) {
            echo var_dump($arr).PHP_EOL;
            echo json_last_error_msg().PHP_EOL;
            echo "Date Empty".date('Y-m-d H:i:s').PHP_EOL;
            return;
        }

        foreach ($arr['BusinessUnit'] as $row) {
            if (empty($row['BUGUID'])) {//BUGUID为空跳过不操作
                continue;
            }
            //空值数据转换
            foreach ($row as $col => $val) {
                if (
                    (strpos($col, 'GUID') !== false || in_array($col,
                            ['CreatedOn', 'CreatedBy', 'ModifiedOn', 'ModifiedBy']))
                    && empty($val)
                ) {
                    $row[$col] = NULL;
                }elseif ($val == 'True') {
                    $row[$col] = 1;
                }elseif ($val == 'False') {
                    $row[$col] = 0;
                }
            }

            $fieldArr = [
                ':BUGUID' => $row['BUGUID'],
                ':BUName' => $row['BUName'],
                ':BUFullName' => $row['BUFullName'],
                ':BUCode' => $row['BUCode'],
                ':HierarchyCode' => $row['HierarchyCode'],
                ':ParentGUID' => $row['ParentGUID'],
                ':WebSite' => $row['WebSite'],
                ':Fax' => $row['Fax'],
                ':CompanyAddr' => $row['CompanyAddr'],
                ':Charter' => $row['Charter'],
                ':CorporationDeputy' => $row['CorporationDeputy'],
                ':CreatedOn' => $row['CreatedOn'],
                ':CreatedBy' => $row['CreatedBy'],
                ':ModifiedOn' => $row['ModifiedOn'],
                ':ModifiedBy' => $row['ModifiedBy'],
                ':Comments' => $row['Comments'],
                ':IsEndCompany' => $row['IsEndCompany'],
                ':IsCompany' => $row['IsCompany'],
                ':Level' => $row['Level'],
                ':BUType' => $row['BUType'],
                ':ProjGUID' => $row['ProjGUID'],
                ':OrderCode' => $row['OrderCode'],
                ':OrderHierarchyCode' => $row['OrderHierarchyCode'],
                ':CompanyGUID' => $row['CompanyGUID'],
                ':NamePath' => $row['NamePath'],
                ':FyStationGUID' => $row['FyStationGUID'],
                ':RefStationName' => $row['RefStationName'],
                ':is_valid' => $row['is_valid'],
                ':Zyx' => $row['Zyx'],
                ':IsZs' => $row['IsZs'],
                ':IsFc' => $row['IsFc'],
                ':BUPersonInCharge' => $row['BUPersonInCharge'],
                ':ParentReportGUID' => $row['ParentReportGUID'],
                ':PrincipalGUID' => $row['PrincipalGUID'],
                ':MainBuGUID' => $row['MainBuGUID'],
                ':BusinessNum' => $row['BusinessNum']
            ];

            $insertField = [
                'BUGUID' => $row['BUGUID'],
                'BUName' => $row['BUName'],
                'BUFullName' => $row['BUFullName'],
                'BUCode' => $row['BUCode'],
                'HierarchyCode' => $row['HierarchyCode'],
                'ParentGUID' => $row['ParentGUID'],
                'WebSite' => $row['WebSite'],
                'Fax' => $row['Fax'],
                'CompanyAddr' => $row['CompanyAddr'],
                'Charter' => $row['Charter'],
                'CorporationDeputy' => $row['CorporationDeputy'],
                'CreatedOn' => $row['CreatedOn'],
                'CreatedBy' => $row['CreatedBy'],
                'ModifiedOn' => $row['ModifiedOn'],
                'ModifiedBy' => $row['ModifiedBy'],
                'Comments' => $row['Comments'],
                'IsEndCompany' => $row['IsEndCompany'],
                'IsCompany' => $row['IsCompany'],
                'Level' => $row['Level'],
                'BUType' => $row['BUType'],
                'ProjGUID' => $row['ProjGUID'],
                'OrderCode' => $row['OrderCode'],
                'OrderHierarchyCode' => $row['OrderHierarchyCode'],
                'CompanyGUID' => $row['CompanyGUID'],
                'NamePath' => $row['NamePath'],
                'FyStationGUID' => $row['FyStationGUID'],
                'RefStationName' => $row['RefStationName'],
                'is_valid' => $row['is_valid'],
                'Zyx' => $row['Zyx'],
                'IsZs' => $row['IsZs'],
                'IsFc' => $row['IsFc'],
                'BUPersonInCharge' => $row['BUPersonInCharge'],
                'ParentReportGUID' => $row['ParentReportGUID'],
                'PrincipalGUID' => $row['PrincipalGUID'],
                'MainBuGUID' => $row['MainBuGUID'],
                'BusinessNum' => $row['BusinessNum']
            ];
            $conn = ErpBusinessUnitEntity::getDb();
            $sql = 'select BUGUID,BUName from myscrm_erp_business_unit where BUGUID=:BUGUID';
            $data = $conn -> createCommand($sql, [':BUGUID' => $row['BUGUID']]) -> queryOne();

            if (!empty($data)){ // 更新
                $sql = 'update myscrm_erp_business_unit set BUName=:BUName,BUFullName=:BUFullName,'.
                    'BUCode=:BUCode,HierarchyCode=:HierarchyCode,ParentGUID=:ParentGUID,'.
                    'WebSite=:WebSite,Fax=:Fax,CompanyAddr=:CompanyAddr,Charter=:Charter,CorporationDeputy=:CorporationDeputy,CreatedOn=:CreatedOn, '.
                    'CreatedBy=:CreatedBy,ModifiedOn=:ModifiedOn,ModifiedBy=:ModifiedBy,Comments=:Comments,IsEndCompany=:IsEndCompany,'.
                    'IsCompany=:IsCompany,Level=:Level,BUType=:BUType,ProjGUID=:ProjGUID,OrderCode=:OrderCode,'.
                    'OrderHierarchyCode=:OrderHierarchyCode,CompanyGUID=:CompanyGUID,NamePath=:NamePath,FyStationGUID=:FyStationGUID,RefStationName=:RefStationName,'.
                    'is_valid=:is_valid,Zyx=:Zyx,IsZs=:IsZs,IsFc=:IsFc,'.
                    'BUPersonInCharge=:BUPersonInCharge,ParentReportGUID=:ParentReportGUID,PrincipalGUID=:PrincipalGUID,MainBuGUID=:MainBuGUID,BusinessNum=:BusinessNum '.
                    'where BUGUID=:BUGUID';
                $conn->createCommand($sql, $fieldArr)->execute();
            } else{//新增
                $conn->createCommand()->insert('myscrm_erp_business_unit', $insertField)->execute();
                $msg .= "created business_unit:".$row['BUGUID']."".PHP_EOL;
            }
        }
        echo date('Y-m-d H:i:s').$msg." Success!";
	}
    
    /**
     * 同步abu相关信息
     */
    public function actionUpdateErpAbu()
    {
        ini_set('max_execution_time', 1200);
        ini_set('default_socket_timeout', 600);
        ini_set('memory_limit', '1280M');

        $wsdl = "http://ekp.mingyuanyun.com/EKPWebService/AdUserService.asmx?wsdl";
        $conn = ErpUserEntity::getDb();
        $str = $msg = "";
        
        $soap = new \SoapClient($wsdl);
        $obj = $soap->GetMyUserAllCol();

        $str = preg_replace('/\s*/', '', $obj->GetMyUserAllColResult);
        $AllInfo = Json::decode(stripcslashes($str), true);
        if (empty($AllInfo)) {
            echo var_dump($AllInfo).PHP_EOL;
            echo json_last_error_msg().PHP_EOL;
            echo "date Empty".date('Y-m-d H:i:s').PHP_EOL;
            return;
        }

        foreach ($AllInfo['myUser'] as $value) {
            if (empty($value['UserGUID'])) {
                continue;
            }
            if (!empty($value['CreatedOn']) && strlen(trim($value['CreatedOn'])) != 19) {
                if(strpos($value['CreatedOn'],'/')){
                    $value['CreatedOn'] = date('Y-m-d H:i:s',strtotime($value['CreatedOn']));
                }else{
                    $value['CreatedOn'] = substr($value['CreatedOn'],0,10)." ".substr($value['CreatedOn'],10);
                }
            } elseif (empty($value['CreatedOn'])) {
                $value['CreatedOn'] = "1970-01-01 00:00:00";
            }
            if (!empty($value['ModifiedOn']) && strlen(trim($value['ModifiedOn'])) != 19) {
                $value['ModifiedOn'] = substr($value['ModifiedOn'],0,10)." ".substr($value['ModifiedOn'],10);
            } elseif (empty($value['ModifiedOn'])) {
                $value['ModifiedOn'] = "1970-01-01 00:00:00";
            }
            $value['IsDisabeld'] = $value['IsDisabeld'] == "True" ?  1 : 0;
            $value['IsAdmin'] = $value['IsAdmin'] == "True" ?  1 : 0;
            $value['IsSaler'] = $value['IsSaler'] == "True" ?  1 : 0;
            $value['IsAdvanceUser'] = $value['IsAdvanceUser'] == "True" ?  1 : 0;
            empty($value['IsUserChangePWD']) && $value['IsUserChangePWD'] = 0;
            empty($value['IsLocked']) && $value['IsLocked'] = 0;
            empty($value['IsMobileUser']) && $value['IsMobileUser'] = 0;

            $fieldArr = [
                ':UserGUID' => $value['UserGUID'],
                ':AbuName' => $value['AbuName'],
                ':AbuFzrName' => $value['AbuFzrName'],
                ':DeptmentFzrName' => $value['DeptmentFzrName'],
                ':AbuGUID' => $value['AbuGUID'],
                ':ABuFzrID' => $value['ABuFzrID'],
                ':DeptmentFzrID' => $value['DeptmentFzrID'],
                ':UserCode' => $value['UserCode'],
                ':UserName' => $value['UserName'],
                ':BUGUID' => $value['BUGUID'],
                ':PhotoUrl' => $value['PhotoUrl'],
                ':JobTitle' => $value['JobTitle'],
                ':Email' => $value['Email'],
                ':OfficePhone' => $value['OfficePhone'],
                ':MobilePhone' => $value['MobilePhone'],
                ':HomePhone' => $value['HomePhone'],
                ':ADAccount' => $value['ADAccount'],
                ':CreatedOn' => $value['CreatedOn'],
                ':ModifiedOn' => $value['ModifiedOn'],
                ':CreatedBy' => $value['CreatedBy'],
                ':ModifiedBy' => $value['ModifiedBy'],
                ':IsDisabeld' => $value['IsDisabeld'],
                ':DisabledReason' => $value['DisabledReason'],
                ':Comments' => $value['Comments'],
                ':ParentGUID' => $value['ParentGUID'],
                ':Password' => $value['Password'],
                ':IsAdmin' => $value['IsAdmin'],
                ':IsSaler' => $value['IsSaler'],
                ':JobNumber' => $value['JobNumber'],
                ':DepartmentGUID' => $value['DepartmentGUID'],
                ':UserProject' => $value['UserProject'],
                ':IsAdvanceUser' => $value['IsAdvanceUser'],
                ':DefaultStation' => $value['DefaultStation'],
                ':UserKind' => $value['UserKind'],
                //':JoinDate' => $value['JoinDate'],
                //':CheckUserCode' => $value['CheckUserCode'],
                //':keySN' => $value['keySN'],
                //':lzDate' => $value['lzDate'],
                //':RegularizedDate' => $value['RegularizedDate'],
                //':HjCount' => $value['HjCount'],
                //':DeviceID' => $value['DeviceID'],
                //':DeviceID2' => $value['DeviceID2'],
                //':StockRate' => $value['StockRate'],
                //':tuid' => $value['tuid'],
                ':Zyx' => $value['Userzyx'],
                //':PSWModifyTime' => $value['PSWModifyTime'],
                ':IsUserChangePWD' => $value['IsUserChangePWD'],
                ':IsLocked' => $value['IsLocked'],
                ':IsMobileUser' => $value['IsMobileUser'],
                //':LockTime' => $value['LockTime'],
                //':UserNum' => $value['UserNum']
            ];

            $insertField = [
                'UserGUID' => $value['UserGUID'],
                'AbuName' => $value['AbuName'],
                'AbuFzrName' => $value['AbuFzrName'],
                'DeptmentFzrName' => $value['DeptmentFzrName'],
                'AbuGUID' => $value['AbuGUID'],
                'ABuFzrID' => $value['ABuFzrID'],
                'DeptmentFzrID' => $value['DeptmentFzrID'],
                'UserCode' => $value['UserCode'],
                'UserName' => $value['UserName'],
                'BUGUID' => $value['BUGUID'],
                'PhotoUrl' => $value['PhotoUrl'],
                'JobTitle' => $value['JobTitle'],
                'Email' => $value['Email'],
                'OfficePhone' => $value['OfficePhone'],
                'MobilePhone' => $value['MobilePhone'],
                'HomePhone' => $value['HomePhone'],
                'ADAccount' => $value['ADAccount'],
                'CreatedOn' => $value['CreatedOn'],
                'ModifiedOn' => $value['ModifiedOn'],
                'CreatedBy' => $value['CreatedBy'],
                'ModifiedBy' => $value['ModifiedBy'],
                'IsDisabeld' => $value['IsDisabeld'],
                'DisabledReason' => $value['DisabledReason'],
                'Comments' => $value['Comments'],
                'ParentGUID' => $value['ParentGUID'],
                'Password' => $value['Password'],
                'IsAdmin' => $value['IsAdmin'],
                'IsSaler' => $value['IsSaler'],
                'JobNumber' => $value['JobNumber'],
                'DepartmentGUID' => $value['DepartmentGUID'],
                'UserProject' => $value['UserProject'],
                'IsAdvanceUser' => $value['IsAdvanceUser'],
                'DefaultStation' => $value['DefaultStation'],
                'UserKind' => $value['UserKind'],
                //'JoinDate' => $value['JoinDate'],
                //'CheckUserCode' => $value['CheckUserCode'],
                //'keySN' => $value['keySN'],
                //'lzDate' => $value['lzDate'],
                //'RegularizedDate' => $value['RegularizedDate'],
                //'HjCount' => $value['HjCount'],
                'DeviceID' => 0,
                'DeviceID2' => 0,
                //'StockRate' => $value['StockRate'],
                //'tuid' => $value['tuid'],
                'Zyx' => $value['Userzyx'],
                //'PSWModifyTime' => $value['PSWModifyTime'],
                'IsUserChangePWD' => $value['IsUserChangePWD'],
                'IsLocked' => $value['IsLocked'],
                'IsMobileUser' => $value['IsMobileUser'],
                //'LockTime' => $value['LockTime'],
                'UserNum' => 0
            ];

            $sel = 'select UserGUID,UserCode from myscrm_erp_user where UserGUID=:UserGUID';
            $data = $conn->createCommand($sel, [':UserGUID' => $value['UserGUID']])->queryOne();
            
            if (!empty($data)){ // 更新
                $sql = 'update myscrm_erp_user set AbuName=:AbuName,AbuFzrName=:AbuFzrName,DeptmentFzrName=:DeptmentFzrName, '.
                    'AbuGUID=:AbuGUID,ABuFzrID=:ABuFzrID,DeptmentFzrID=:DeptmentFzrID,'.
                    'UserCode=:UserCode, UserName=:UserName, BUGUID=:BUGUID, PhotoUrl=:PhotoUrl, JobTitle=:JobTitle, Email=:Email, '.
                    'OfficePhone=:OfficePhone, MobilePhone=:MobilePhone, HomePhone=:HomePhone, ADAccount=:ADAccount, CreatedOn=:CreatedOn, '.
                    'ModifiedOn=:ModifiedOn, CreatedBy=:CreatedBy, ModifiedBy=:ModifiedBy, IsDisabeld=:IsDisabeld,DisabledReason=:DisabledReason, '.
                    'Comments=:Comments, ParentGUID=:ParentGUID, IsAdmin=:IsAdmin, IsSaler=:IsSaler, JobNumber=:JobNumber, '.
                    'DepartmentGUID=:DepartmentGUID, UserProject=:UserProject, IsAdvanceUser=:IsAdvanceUser, DefaultStation=:DefaultStation, '.
                    'UserKind=:UserKind, Zyx=:Zyx, IsUserChangePWD=:IsUserChangePWD, IsLocked=:IsLocked, IsMobileUser=:IsMobileUser, '.
                    'Password=:Password '.
                    //'JoinDate=:JoinDate, CheckUserCode=:CheckUserCode, keySN=:keySN, lzDate=:lzDate, RegularizedDate=:RegularizedDate, HjCount=:HjCount, DeviceID=:DeviceID, DeviceID2=:DeviceID2, StockRate=:StockRate, tuid=:tuid, LockTime=:LockTime, UserNum=:UserNum, PSWModifyTime=:PSWModifyTime, '.
                    'where UserGUID=:UserGUID';

                $conn->createCommand($sql, $fieldArr)->execute();
            } else{
                $conn->createCommand()->insert('myscrm_erp_user', $insertField)->execute();   
                $msg .= "created user".$value['UserGUID'].":".$value['UserName']."\r\n";
            }
        }
        echo date('Y-m-d H:i:s').$msg." Success!";

        try {
            /* @var $contactService ContactService */
            $contactService = \Yii::createObject(ContactService::className());
            $contactService->updateOrganizationContact();
            echo date('Y-m-d H:i:s') . "更新 myscrm_organization 表数据成功";
        } catch (\Exception $e) {
            echo date('Y-m-d H:i:s') . "更新 myscrm_organization 表数据失败" . $e->getMessage();
        }
    }
    
    public function actionTest ()
    {
        echo "ok!";
    }
    
    /**
     * 生成合同项编号
     */
    public function actionDoRevenue ()
    {
        $sql = "select * from myscrm_contract_revenue ";
        $conn = ErpUserEntity::getDb();
        $data = $conn->createCommand($sql)->queryAll();
        
        foreach ($data as $v) {
            if (!empty($v['income_code'])){
                continue;
            }
            $sqla = "select inc, contract_code from myscrm_contract_manage where contract_id='".$v['contract_id']."'";
            $data = $conn->createCommand($sqla)->queryOne();
            $data['inc'] = ($data['inc'] == 0 ? 1 : ++$data['inc']);
            $data['inc'] < 10 && $data['inc'] = "0".$data['inc'];
            $v['income_code'] = $data['contract_code']."-SR-".$data['inc'];
            
            $sqlb = "update myscrm_contract_manage set inc=".$data['inc']." where contract_id='".$v['contract_id']."'";
            $conn->createCommand($sqlb)->execute();
            $sqlc = "update myscrm_contract_revenue set income_code='".$v['income_code']."' where revenue_id='".$v['revenue_id']."'";
            $conn->createCommand($sqlc)->execute();
            
        }
        
        echo "ok!";
    }

}